//
//  ZBLivePreview.m
//  ZhiBo
//
//  Created by huangtie on 2017/11/2.
//  Copyright © 2017年 huangtie. All rights reserved.
//

#import "ZBLivePreview.h"
#import <PLVStreamerAPI/PLVStreamerAPI.h>
#import "ZBLiveChannel.h"
#import "ZBLiveStatisticsItem.h"
#import "MarqueeLabel.h"
#import "ZBLiveMarquee.h"

inline static NSString *formatedSpeed(float bytes, float elapsed_milli) {
    if (elapsed_milli <= 0) {
        return @"N/A";
    }
    
    if (bytes <= 0) {
        return @"0 KB/s";
    }
    
    float bytes_per_sec = ((float)bytes) * 1000.f /  elapsed_milli;
    if (bytes_per_sec >= 1000 * 1000) {
        return [NSString stringWithFormat:@"%.2fMB/s", ((float)bytes_per_sec) / 1000 / 1000];
    } else if (bytes_per_sec >= 1000) {
        return [NSString stringWithFormat:@"%.1fKB/s", ((float)bytes_per_sec) / 1000];
    } else {
        return [NSString stringWithFormat:@"%ldB/s", (long)bytes_per_sec];
    }
}

@interface ZBLivePreview ()<LFLiveSessionDelegate,ZBLiveMarqueeDelegate>

// 单流模式
@property (nonatomic, getter=isAloneMode) NSInteger aloneMode;

@property (nonatomic, strong) UIButton *beautyButton;
@property (nonatomic, strong) UIButton *cameraButton;
@property (nonatomic, strong) UIButton *closeButton;
@property (nonatomic, strong) UIButton *waterMarkButton;
@property (nonatomic, strong) UIButton *startLiveButton;
@property (nonatomic, strong) UIView *containerView;
@property (nonatomic, strong) LFLiveDebug *debugInfo;
@property (nonatomic, strong) LFLiveSession *session;
@property (nonatomic, strong) UILabel *stateLabel;

@property (nonatomic, strong) UILabel *rateLabel;
@property (nonatomic, strong) UILabel *videoBitRate;
@property (nonatomic, strong) UILabel *audioBitRate;

@property (nonatomic , strong) UILabel *timeLabel;
@property (nonatomic , strong) UIButton *quitBtn;
@property (nonatomic , strong) UIView *topRect;
@property (nonatomic , strong) UIView *statisticsRect;
@property (nonatomic , strong) UIView *toolsRect;

@property (nonatomic , strong) ZBLiveStatisticsItem *commentItem;
@property (nonatomic , strong) ZBLiveStatisticsItem *userItem;
@property (nonatomic , strong) ZBLiveStatisticsItem *zanItem;

@property (nonatomic , strong) UIButton *cameraBtn;
@property (nonatomic , strong) UIButton *voiceBtn;
@property (nonatomic , strong) UIButton *flashBtn;

@property (nonatomic , strong) UIView *noticRect;
@property (nonatomic , strong) MarqueeLabel *marqueeLabel;
@property (nonatomic , strong) ZBLiveMarquee *marqueeView;

@end

@implementation ZBLivePreview



- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        self.backgroundColor = [UIColor blackColor];
        [self requestAccessForVideo];
        [self requestAccessForAudio];
        [self addSubview:self.containerView];
//        [self.containerView addSubview:self.stateLabel];
//        [self.containerView addSubview:self.closeButton];
//        [self.containerView addSubview:self.cameraButton];
//        [self.containerView addSubview:self.beautyButton];
//        [self.containerView addSubview:self.waterMarkButton];
//        [self.containerView addSubview:self.rateLabel];
//        [self.containerView addSubview:self.startLiveButton];
        
        [self.containerView addSubview:self.topRect];
//        [self.containerView addSubview:self.statisticsRect];
        [self.containerView addSubview:self.toolsRect];
        [self.containerView addSubview:self.noticRect];

        self.topRect.userInteractionEnabled = YES;
    }
    return self;
}

- (void)startLive
{
    // 配置推流Info
    LFLiveStreamInfo *stream = [LFLiveStreamInfo new];
    stream.url = [ZBLiveChannel sharedInstance].rtmpUrl;
    [self.session startLive:stream];
    // 设置为单流模式
    [self configAloneSteamMode];
}

#pragma mark GET-SET
- (UIView *)statisticsRect
{
    if (!_statisticsRect) {
        self.commentItem = [[ZBLiveStatisticsItem alloc] initIconName:@"live_msg"];
        [self.commentItem layoutSelf:0];
        [self.commentItem addTarget:self action:@selector(itemClick:) forControlEvents:UIControlEventTouchUpInside];
        self.userItem = [[ZBLiveStatisticsItem alloc] initIconName:@"live_user"];
        [self.userItem layoutSelf:0];
        self.userItem.top = self.commentItem.bottom;
        [self.userItem addTarget:self action:@selector(itemClick:) forControlEvents:UIControlEventTouchUpInside];
        self.zanItem = [[ZBLiveStatisticsItem alloc] initIconName:@"live_heard"];
        [self.zanItem layoutSelf:0];
        self.zanItem.top = self.userItem.bottom;
        [self.zanItem addTarget:self action:@selector(itemClick:) forControlEvents:UIControlEventTouchUpInside];
        
        _statisticsRect = [[UIView alloc] init];
        _statisticsRect.size = CGSizeMake(self.commentItem.width, self.commentItem.height * 3);
        _statisticsRect.backgroundColor = [UIColor clearColor];
        _statisticsRect.right = self.containerView.width;
        _statisticsRect.centerY = self.containerView.height / 2;
        [_statisticsRect addSubview:self.commentItem];
        [_statisticsRect addSubview:self.userItem];
        [_statisticsRect addSubview:self.zanItem];
    }
    return _statisticsRect;
}

- (UIView *)toolsRect
{
    if (!_toolsRect) {
        self.cameraBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [self.cameraBtn setBackgroundImage:[UIImage imageNamed:@"live_xiangji"] forState:UIControlStateNormal];
        [self.cameraBtn setBackgroundImage:[UIImage imageNamed:@"live_xiangji"] forState:UIControlStateSelected];
        [self.cameraBtn sizeToFit];
        [self.cameraBtn addTarget:self action:@selector(cameraClick) forControlEvents:UIControlEventTouchUpInside];
        
        self.voiceBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [self.voiceBtn setBackgroundImage:[UIImage imageNamed:@"live_hutong"] forState:UIControlStateNormal];
        [self.voiceBtn setBackgroundImage:[UIImage imageNamed:@"live_hutong_s"] forState:UIControlStateSelected];
        [self.voiceBtn sizeToFit];
        [self.voiceBtn addTarget:self action:@selector(voiceClick) forControlEvents:UIControlEventTouchUpInside];
        
        self.flashBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [self.flashBtn setBackgroundImage:[UIImage imageNamed:@"live_shaguangddeng_s"] forState:UIControlStateNormal];
        [self.flashBtn setBackgroundImage:[UIImage imageNamed:@"live_shaguangddeng"] forState:UIControlStateSelected];
        [self.flashBtn sizeToFit];
        [self.flashBtn addTarget:self action:@selector(flashClick) forControlEvents:UIControlEventTouchUpInside];
        
        _toolsRect = [[UIView alloc] init];
        _toolsRect.size = CGSizeMake(self.containerView.width - 120, 110);
        _toolsRect.bottom = self.containerView.height;
        _toolsRect.centerX = self.containerView.width / 2;
        self.cameraBtn.left = 0;
        self.cameraBtn.centerY = _toolsRect.height / 2;
        self.voiceBtn.centerX = _toolsRect.width / 2;
        self.voiceBtn.centerY = _toolsRect.height / 2;
        self.flashBtn.right = _toolsRect.width;
        self.flashBtn.centerY = _toolsRect.height / 2;
        [_toolsRect addSubview:self.cameraBtn];
        [_toolsRect addSubview:self.voiceBtn];
        [_toolsRect addSubview:self.flashBtn];
    }
    return _toolsRect;
}

- (UIView *)topRect
{
    if (!_topRect) {
        _topRect = [[UILabel alloc] init];
        _topRect.size = CGSizeMake(self.containerView.width, 100);
        _topRect.backgroundColor = [UIColor clearColor];
        
        self.quitBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        self.quitBtn.size = CGSizeMake(40, 40);
        [self.quitBtn setImage:[UIImage imageNamed:@"cancel"] forState:UIControlStateNormal];
        [self.quitBtn addTarget:self action:@selector(quitClick) forControlEvents:UIControlEventTouchUpInside];
        self.quitBtn.right = _topRect.width - 18;
        self.quitBtn.centerY = _topRect.height / 2;
        [_topRect addSubview:self.quitBtn];
        
        self.timeLabel = [[UILabel alloc] init];
        self.timeLabel.size = CGSizeMake(200, 20);
        self.timeLabel.font = FONT_NORMAL_18;
        self.timeLabel.textColor = UICOLOR_ARGB(0xffffffff);
        self.timeLabel.left = 20;
        self.timeLabel.centerY = _topRect.height / 2;
        [_topRect addSubview:self.timeLabel];
    }
    return _topRect;
}

- (UIView *)noticRect
{
    if (!_noticRect) {
        _noticRect = [[UIView alloc] initWithFrame:CGRectMake(20, self.topRect.bottom - 20, self.containerView.width - 100, 20)];
        UIImageView *icon = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"live_tongzhi"]];
        [icon sizeToFit];
        icon.centerY = _noticRect.height / 2;
        _noticRect.hidden = YES;
        [_noticRect addSubview:icon];
        
//        _marqueeLabel = [[MarqueeLabel alloc] initWithFrame:CGRectMake(icon.right + 10,0,0,20)];
//        _marqueeLabel.width = _noticRect.width - _marqueeLabel.left;
//        _marqueeLabel.marqueeType = MLContinuous;
//        _marqueeLabel.scrollDuration = 10.0;
//        _marqueeLabel.animationCurve = UIViewAnimationOptionCurveEaseInOut;
//        _marqueeLabel.fadeLength = 50;
//        _marqueeLabel.continuousMarqueeExtraBuffer = 5.0f;
//        _marqueeLabel.font = [UIFont systemFontOfSize:14.0f];
//        _marqueeLabel.textColor = UICOLOR_ARGB(0xffe84f48);
//        _marqueeLabel.backgroundColor = [UIColor clearColor];
//        _marqueeLabel.tag = 101;
//        [_noticRect addSubview:_marqueeLabel];
        
        self.marqueeView = [[ZBLiveMarquee alloc] initWithSize:CGSizeMake(_noticRect.width - icon.right - 10, 20) font:FONT_NORMAL_14 textColor:UICOLOR_ARGB(0xffe84f48)];
        self.marqueeView.left = icon.right + 10;
        self.marqueeView.delegate = self;
        [_noticRect addSubview:self.marqueeView];
    }
    return _noticRect;
}

#pragma mark ACTION
- (void)itemClick:(UIButton *)button
{
    NSInteger index = [self.statisticsRect.subviews indexOfObject:button];
    switch (index) {
        case 0:{
                
            }
            break;
    }
}

- (void)cameraClick
{
    self.cameraBtn.selected = !self.cameraBtn.selected;
    AVCaptureDevicePosition devicePositon = self.session.captureDevicePosition;
    self.session.captureDevicePosition = (devicePositon == AVCaptureDevicePositionBack) ? AVCaptureDevicePositionFront : AVCaptureDevicePositionBack;
}

- (void)voiceClick
{
    self.voiceBtn.selected = !self.voiceBtn.selected;
    [self.session setMuted:self.voiceBtn.selected];
}

- (void)flashClick
{
    self.flashBtn.selected = !self.flashBtn.selected;
    [self.session setTorch:self.flashBtn.selected];
}

- (void)quitClick
{
    [self.delegate livePreviewDidClickQunit];
}

#pragma mark METHOD
- (void)refreshTimeLabel:(NSString *)text
{
    self.timeLabel.text = text;
}

- (void)refreshNoticeText:(NSString *)text
{
    if (text.length) {
        self.noticRect.hidden = NO;
        NSString *string = [NSString stringWithFormat:@"消息提醒：%@",text];
        [self.marqueeView begin:string];
//        self.marqueeLabel.text = string;
//        [self.marqueeLabel restartLabel];
        
    }
}

#pragma mark -- Public Method
- (void)requestAccessForVideo {
    __weak typeof(self) _self = self;
    AVAuthorizationStatus status = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    switch (status) {
        case AVAuthorizationStatusNotDetermined: {
            // 许可对话没有出现，发起授权许可
            [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
                if (granted) {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [_self.session setRunning:YES];
                    });
                }
            }];
            break;
        }
        case AVAuthorizationStatusAuthorized: {
            // 已经开启授权，可继续
            dispatch_async(dispatch_get_main_queue(), ^{
                [_self.session setRunning:YES];
            });
            break;
        }
        case AVAuthorizationStatusDenied:
        case AVAuthorizationStatusRestricted:
            // 用户明确地拒绝授权，或者相机设备无法访问
            
            break;
        default:
            break;
    }
}

- (void)requestAccessForAudio {
    AVAuthorizationStatus status = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeAudio];
    switch (status) {
        case AVAuthorizationStatusNotDetermined: {
            [AVCaptureDevice requestAccessForMediaType:AVMediaTypeAudio completionHandler:^(BOOL granted) {
            }];
            break;
        }
        case AVAuthorizationStatusAuthorized: {
            break;
        }
        case AVAuthorizationStatusDenied:
        case AVAuthorizationStatusRestricted:
            break;
        default:
            break;
    }
}

#pragma mark -- LFStreamingSessionDelegate
/** live status changed will callback */
- (void)liveSession:(nullable LFLiveSession *)session liveStateDidChange:(LFLiveState)state {
    NSLog(@"liveStateDidChange: %ld", state);
    switch (state) {
            
        case LFLiveReady:
        case LFLiveStop: {
            _stateLabel.text = @"未连接";
            [self.startLiveButton setTitle:@"开始直播" forState:UIControlStateNormal];
            [self.startLiveButton setBackgroundColor:[UIColor colorWithRed:50 green:32 blue:245 alpha:1]];
            _rateLabel.text = @"0KB/s";
        }
            break;
        case LFLivePending:
            _stateLabel.text = @"连接中";
            break;
        case LFLiveStart: {
            _stateLabel.text = @"已连接";
            [self.startLiveButton setTitle:@"结束直播" forState:UIControlStateNormal];
            [self.startLiveButton setBackgroundColor:[UIColor redColor]];
        }
            
            break;
        case LFLiveError: {
            _stateLabel.text = @"连接错误";
            [self.startLiveButton setBackgroundColor:[UIColor colorWithRed:50 green:32 blue:245 alpha:1]];
            [self.startLiveButton setTitle:@"开始直播" forState:UIControlStateNormal];
            _rateLabel.text = @"0KB/s";
            [self.delegate liveDidConnectError];
        }
            break;
            
        default:
            break;
    }
}

/** live debug info callback */
- (void)liveSession:(nullable LFLiveSession *)session debugInfo:(nullable LFLiveDebug *)debugInfo {
    NSString *speed  = formatedSpeed(debugInfo.currentBandwidth, debugInfo.elapsedMilli);
    self.rateLabel.text = [NSString stringWithFormat:@"↑%@",speed];
    //self.videoBitRate.text = [NSString stringWithFormat:@"v bit:%u",session.streamInfo.videoConfiguration.videoBitRate];
    SMLog("debugInfo: %@ %@", speed,debugInfo)
}

/** callback socket errorcode */
- (void)liveSession:(nullable LFLiveSession *)session errorCode:(LFLiveSocketErrorCode)errorCode {
    SMLog(@"errorCode: %ld", errorCode);
}

#pragma mark -- Getter Setter
- (LFLiveSession *)session {
    if (!_session) {
        LFLiveVideoConfiguration *videoConfig = [LFLiveVideoConfiguration new];
        LFLiveAudioConfiguration *audioConfig = [LFLiveAudioConfiguration new];
        audioConfig.numberOfChannels = 2;   // 声道数
        
        switch (self.videoQuality) {
            case 0: {       // 360p 上行带宽速率30KB/s左右
                
                // 视频配置
                videoConfig.videoSize = (_supportedInterfaceOrientation==UIInterfaceOrientationPortrait)?CGSizeMake(240, 426):CGSizeMake(426, 240);
                videoConfig.videoFrameRate = 25;
                videoConfig.videoBitRate = 300*1024;
                videoConfig.videoMaxKeyframeInterval = 50;
                videoConfig.sessionPreset = LFCaptureSessionPreset360x640;
                
                // 音频配置
                audioConfig.audioSampleRate = LFLiveAudioSampleRate_16000Hz;
                audioConfig.audioBitrate = LFLiveAudioBitRate_64Kbps;
            }
                break;
            case 1: {       // 540p 上行带宽速率50KB/s左右
                
                videoConfig.videoSize = (_supportedInterfaceOrientation==UIInterfaceOrientationPortrait)?CGSizeMake(360, 640):CGSizeMake(640, 360);
                videoConfig.videoFrameRate = 25;
                videoConfig.videoBitRate = 400*1024;
                videoConfig.videoMaxKeyframeInterval = 50;
                videoConfig.sessionPreset = LFCaptureSessionPreset360x640;
                
                audioConfig.audioSampleRate = LFLiveAudioSampleRate_44100Hz;
                audioConfig.audioBitrate = LFLiveAudioBitRate_96Kbps;
            }
                break;
            case 2: {       // 540p 上行带宽速率75KB/s左右
                
                videoConfig.videoSize = (_supportedInterfaceOrientation==UIInterfaceOrientationPortrait)?CGSizeMake(540, 960):CGSizeMake(960, 540);
                videoConfig.videoFrameRate = 25;
                videoConfig.videoBitRate = 600*1024;
                videoConfig.videoMaxBitRate = 800*1024;
                videoConfig.videoMinBitRate = 400*1024;
                videoConfig.videoMaxKeyframeInterval = 50;
                videoConfig.sessionPreset = LFCaptureSessionPreset540x960;
                
                audioConfig.audioSampleRate = LFLiveAudioSampleRate_44100Hz;
                audioConfig.audioBitrate = LFLiveAudioBitRate_96Kbps;
            }
                break;
            case 3: {       // 540p 上行带宽速率100KB/s左右
                
                videoConfig.videoSize = (_supportedInterfaceOrientation==UIInterfaceOrientationPortrait)?CGSizeMake(540, 960):CGSizeMake(960, 540);
                videoConfig.videoFrameRate = 20;
                videoConfig.videoBitRate = 800*1024;
                videoConfig.videoMaxBitRate = 1100*1024;
                videoConfig.videoMinBitRate = 500*1024;
                videoConfig.videoMaxKeyframeInterval = 40;
                videoConfig.sessionPreset = LFCaptureSessionPreset540x960;
                
                audioConfig.audioSampleRate = LFLiveAudioSampleRate_44100Hz;
                audioConfig.audioBitrate = LFLiveAudioBitRate_96Kbps;
            }
                break;
            case 4: {       // 720p 上行带宽速率112.5KB/s左右
                
                videoConfig.videoSize = (_supportedInterfaceOrientation==UIInterfaceOrientationPortrait)?CGSizeMake(720, 1280):CGSizeMake(1280, 720);
                videoConfig.videoFrameRate = 25;
                videoConfig.videoBitRate = 900*1024;
                videoConfig.videoMaxBitRate = 1200*1024;
                videoConfig.videoMinBitRate = 700*1024;
                videoConfig.videoMaxKeyframeInterval = 50;
                videoConfig.sessionPreset = LFCaptureSessionPreset720x1280;
                
                audioConfig.audioSampleRate = LFLiveAudioSampleRate_44100Hz;
                audioConfig.audioBitrate = LFLiveAudioBitRate_96Kbps;
            }
                break;
            case 5: {       // 720p 上行带宽速率150KB/s左右
                
                videoConfig.videoSize = (_supportedInterfaceOrientation==UIInterfaceOrientationPortrait)?CGSizeMake(720, 1280):CGSizeMake(1280, 720);
                videoConfig.videoFrameRate = 20;
                videoConfig.videoBitRate = 1200*1024;
                videoConfig.videoMaxBitRate = 1500*1024;
                videoConfig.videoMinBitRate = 900*1024;
                videoConfig.videoMaxKeyframeInterval = 40;
                videoConfig.sessionPreset = LFCaptureSessionPreset720x1280;
                
                audioConfig.audioSampleRate = LFLiveAudioSampleRate_48000Hz;
                audioConfig.audioBitrate = LFLiveAudioBitRate_128Kbps;
            }
                break;
                
            default:
                // 可设置为配置2
                break;
        }
        videoConfig.autorotate = YES;
        videoConfig.outputImageOrientation = [UIApplication sharedApplication].statusBarOrientation;
        
        _session = [[LFLiveSession alloc] initWithAudioConfiguration:audioConfig videoConfiguration:videoConfig captureType:LFLiveCaptureDefaultMask];
        _session.captureDevicePosition = AVCaptureDevicePositionBack;   // 开启后置摄像头(默认前置)
        
        
        /**     定制高质量音频96K 分辨率设置为540*960 方向竖屏
         *      竖屏需要改变的参数：videoSize和outputImageOrientation
         */
        /*
         LFLiveAudioConfiguration *audioConfiguration = [LFLiveAudioConfiguration new];
         audioConfiguration.numberOfChannels = 2;
         audioConfiguration.audioBitrate = LFLiveAudioBitRate_96Kbps;
         audioConfiguration.audioSampleRate = LFLiveAudioSampleRate_44100Hz;
         
         LFLiveVideoConfiguration *videoConfiguration = [LFLiveVideoConfiguration new];
         videoConfiguration.videoSize = CGSizeMake(540, 960);
         videoConfiguration.videoBitRate = 800*1024;
         videoConfiguration.videoMaxBitRate = 1000*1024;
         videoConfiguration.videoMinBitRate = 500*1024;
         videoConfiguration.videoFrameRate = 24;
         videoConfiguration.videoMaxKeyframeInterval = 48;
         videoConfiguration.outputImageOrientation = UIInterfaceOrientationPortrait;
         videoConfiguration.sessionPreset = LFCaptureSessionPreset540x960;
         
         _session = [[LFLiveSession alloc] initWithAudioConfiguration:audioConfiguration videoConfiguration:videoConfiguration];
         */
        
        
        /**  定制高质量音频128K 分辨率设置为720*1280 方向横屏 */
        
        /*
         LFLiveAudioConfiguration *audioConfiguration = [LFLiveAudioConfiguration new];
         audioConfiguration.numberOfChannels = 2;
         audioConfiguration.audioBitrate = LFLiveAudioBitRate_128Kbps;
         audioConfiguration.audioSampleRate = LFLiveAudioSampleRate_44100Hz;
         
         LFLiveVideoConfiguration *videoConfiguration = [LFLiveVideoConfiguration new];
         videoConfiguration.videoSize = CGSizeMake(1280, 720);
         videoConfiguration.videoBitRate = 800*1024;
         videoConfiguration.videoMaxBitRate = 1000*1024;
         videoConfiguration.videoMinBitRate = 500*1024;
         videoConfiguration.videoFrameRate = 15;
         videoConfiguration.videoMaxKeyframeInterval = 30;
         videoConfiguration.outputImageOrientation = UIInterfaceOrientationLandscapeLeft;
         videoConfiguration.sessionPreset = LFCaptureSessionPreset720x1280;
         
         _session = [[LFLiveSession alloc] initWithAudioConfiguration:audioConfiguration videoConfiguration:videoConfiguration];
         */
        
        _session.delegate = self;
        _session.showDebugInfo = YES;
        _session.preView = self;
        
        /*本地存储*/
        //        _session.saveLocalVideo = YES;
        //        NSString *pathToMovie = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/Movie.mp4"];
        //        unlink([pathToMovie UTF8String]); // If a file already exists, AVAssetWriter won't let you record new frames, so delete the old movie
        //        NSURL *movieURL = [NSURL fileURLWithPath:pathToMovie];
        //        _session.saveLocalVideoPath = movieURL;
        
        // add watermark
        //[self addWaterMark];
    }
    return _session;
}

/// 水印功能
- (void)addWaterMark {
    
    UIImageView *imageView = [[UIImageView alloc] init];
    imageView.alpha = 0.8;
    imageView.frame = CGRectMake(50, 110, 80, 80);
    imageView.image = [UIImage imageNamed:@"pet"];
    _session.warterMarkView = imageView;
}

- (UIView *)containerView {
    if (!_containerView) {
        _containerView = [UIView new];
        _containerView.frame = self.bounds;
        _containerView.backgroundColor = [UIColor clearColor];
        _containerView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    }
    return _containerView;
}

- (UILabel *)stateLabel {
    if (!_stateLabel) {
        _stateLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 20, 80, 40)];
        _stateLabel.text = @"未连接";
        _stateLabel.textColor = [UIColor whiteColor];
        _stateLabel.font = [UIFont boldSystemFontOfSize:14.f];
    }
    return _stateLabel;
}

- (UIButton *)closeButton {
    if (!_closeButton) {
        _closeButton = [UIButton new];
        _closeButton.size = CGSizeMake(44, 44);
        _closeButton.left = self.width - 10 - _closeButton.width;
        _closeButton.top = 20;
        [_closeButton setImage:[UIImage imageNamed:@"plv_close"] forState:UIControlStateNormal];
        _closeButton.exclusiveTouch = YES;
        __weak typeof(self) weakSelf = self;
        [_closeButton addBlockForControlEvents:UIControlEventTouchUpInside block:^(id sender) {
            
            [weakSelf.session stopLive];
            [weakSelf.viewController dismissViewControllerAnimated:YES completion:nil];
            [weakSelf removeFromSuperview];
        }];
    }
    return _closeButton;
}

- (UIButton *)cameraButton {
    if (!_cameraButton) {
        _cameraButton = [UIButton new];
        _cameraButton.size = CGSizeMake(44, 44);
        _cameraButton.origin = CGPointMake(_closeButton.left - 10 - _cameraButton.width, 20);
        [_cameraButton setImage:[UIImage imageNamed:@"plv_camera"] forState:UIControlStateNormal];
        _cameraButton.exclusiveTouch = YES;
        __weak typeof(self) _self = self;
        [_cameraButton addBlockForControlEvents:UIControlEventTouchUpInside block:^(id sender) {
            AVCaptureDevicePosition devicePositon = _self.session.captureDevicePosition;
            _self.session.captureDevicePosition = (devicePositon == AVCaptureDevicePositionBack) ? AVCaptureDevicePositionFront : AVCaptureDevicePositionBack;
        }];
    }
    return _cameraButton;
}

- (UIButton *)beautyButton {
    if (!_beautyButton) {
        _beautyButton = [UIButton new];
        _beautyButton.size = CGSizeMake(44, 44);
        _beautyButton.origin = CGPointMake(_cameraButton.left - 10 - _beautyButton.width, 20);
        [_beautyButton setImage:[UIImage imageNamed:@"camra_beauty"] forState:UIControlStateNormal];
        [_beautyButton setImage:[UIImage imageNamed:@"camra_beauty_close"] forState:UIControlStateSelected];
        _beautyButton.exclusiveTouch = YES;
        __weak typeof(self) _self = self;
        [_beautyButton addBlockForControlEvents:UIControlEventTouchUpInside block:^(id sender) {
            _self.session.beautyFace = !_self.session.beautyFace;
            _self.beautyButton.selected = !_self.session.beautyFace;
        }];
    }
    return _beautyButton;
}

- (UIButton *)waterMarkButton {
    if (!_waterMarkButton) {
        _waterMarkButton = [UIButton new];
        _waterMarkButton.size = CGSizeMake(44, 44);
        _waterMarkButton.origin = CGPointMake(_beautyButton.left - 10 - _waterMarkButton.width , 20);
        [_waterMarkButton setImage:[UIImage imageNamed:@"plv_watermark_close"] forState:UIControlStateNormal];
        [_waterMarkButton setImage:[UIImage imageNamed:@"plv_watermark"] forState:UIControlStateSelected];
        
        __weak typeof(self)weakSelf = self;
        [_waterMarkButton addBlockForControlEvents:UIControlEventTouchUpInside block:^(id sender) {
            UIButton *button = (UIButton *)sender;
            button.selected = !button.isSelected;
            
            if (button.isSelected) {
                [weakSelf addWaterMark];
            }else {
                weakSelf.session.warterMarkView = nil;
            }
        }];
    }
    return _waterMarkButton;
}

- (UILabel *)rateLabel {
    if (!_rateLabel) {
        _rateLabel = [UILabel new];
        _rateLabel.size = CGSizeMake(70, 25);
        _rateLabel.top = _closeButton.bottom + 10;
        _rateLabel.right = _closeButton.right - 5;
        _rateLabel.text = @"0KB/s";
        _rateLabel.textColor = [UIColor whiteColor];
        _rateLabel.font = [UIFont boldSystemFontOfSize:12.f];
        _rateLabel.textAlignment = NSTextAlignmentRight;
        _rateLabel.adjustsFontSizeToFitWidth = YES;
        _rateLabel.backgroundColor = [UIColor colorWithWhite:0.2 alpha:0.8];
        _rateLabel.layer.cornerRadius = 8.0;
        _rateLabel.layer.masksToBounds = YES;
    }
    return _rateLabel;
}

- (UIButton *)startLiveButton {
    if (!_startLiveButton) {
        _startLiveButton = [UIButton new];
        _startLiveButton.size = CGSizeMake(self.width / 2, 44);
        _startLiveButton.centerX = self.centerX;
        _startLiveButton.bottom = self.height - 50;
        _startLiveButton.layer.cornerRadius = _startLiveButton.height/2;
        [_startLiveButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [_startLiveButton.titleLabel setFont:[UIFont systemFontOfSize:16]];
        [_startLiveButton setTitle:@"开始直播" forState:UIControlStateNormal];
        [_startLiveButton setBackgroundColor:[UIColor colorWithRed:50 green:32 blue:245 alpha:1]];
        _startLiveButton.exclusiveTouch = YES;
        [_startLiveButton addTarget:self action:@selector(startLiveButtonClick) forControlEvents:UIControlEventTouchUpInside];
        
    }
    return _startLiveButton;
}

- (void)startLiveButtonClick {
    switch (_session.state) {
        case LFLiveError:
            [self.session stopLive];
        case LFLiveReady:
        case LFLiveStop: {
            [self.startLiveButton setTitle:@"结束直播" forState:UIControlStateNormal];
            [self.startLiveButton setBackgroundColor:[UIColor redColor]];
            
            // 配置推流Info
            LFLiveStreamInfo *stream = [LFLiveStreamInfo new];
            stream.url = [ZBLiveChannel sharedInstance].rtmpUrl;
            [self.session startLive:stream];
            // 设置为单流模式
            [self configAloneSteamMode];
        }
            break;
            
        case LFLivePending:
        case LFLiveStart:
            [self.session stopLive];
            break;
            
        default:
            break;
    }
}

// 设置单流模式
- (void)configAloneSteamMode {
    
    if (!self.isAloneMode) {
        [PLVStreamerLogin configAloneStreamModeWithChannelId:[ZBLiveChannel sharedInstance].channelId stream:[ZBLiveChannel sharedInstance].streamName success:^(NSString *responseBody) {
            self.aloneMode = YES;
        } failure:^(NSString *failure) {
            // 设置失败，重新请求或重新推流
            NSLog(@"config alone steam mode failed:%@",failure);
        }];
    }
}

- (void)dealloc {
    SMLog();
}

- (void)marqueeDidRunEnd
{
    self.noticRect.hidden = YES;
}

@end
